<!--
 * @页面名称:数据表定义
 * @描述: 
 * @作者: 
 * @Date:
-->
<template>
  <div class="card dataSheet">
    <el-row class="topSearch">
      <el-col :span="6">
        <el-input placeholder="请输入关键字查询" v-model="tableSearchString" @change="onTableSearchChange"></el-input>
      </el-col>
      <el-col :span="5" class="btns">
        <el-button type="primary" @click="add">新增</el-button>
        <el-button @click="edit">修改</el-button>
        <el-button type="danger" @click="del">删除</el-button>
      </el-col>
      <el-button type="primary" @click="exportData(1)" class="exportBtn">导出</el-button>
    </el-row>
    <!-- 表格模块 -->
    <div style="height: 40%">
      <stable :columns="tableSetting.columns" :data="tableSetting.data" @rowClick="rowClick"></stable>
    </div>
    <el-row class="cen-search">
      <el-col :span="6">
        <el-input placeholder="请输入关键字查询" v-model="searchString" @change="onSearchChange"></el-input>
      </el-col>
      <el-col :span="6" class="btns">
        <el-button type="primary" @click="add2">新增</el-button>
        <el-button @click="edit2">修改</el-button>
        <el-button @click="editFiled">修改列名</el-button>
        <el-button type="danger" @click="del2">删除</el-button>
      </el-col>
      <el-button type="primary" @click="exportData(2)" class="exportBtn">导出</el-button>
    </el-row>
    <!-- 表格模块 -->
    <div style="height: calc(60% - 126px)">
      <stable :columns="tableSetting2.columns" :data="tableSetting2.data" @rowClick="rowClick2"></stable>
    </div>
    <!-- 头部新增修改弹出框 -->
    <el-dialog v-model="dialogSetting.visible" :title="dialogSetting.title" width="30%" draggable>
      <el-form label-width="100px" :model="formData" :rules="rules" ref="formRef">
        <el-form-item label="中文表名:" prop="Description">
          <el-input v-model="formData.Description"></el-input>
        </el-form-item>
        <el-form-item label="英文表名:" prop="Name" v-if="dialogSetting.title !== '编辑'">
          <el-input v-model="formData.Name">
            <template #prepend>
              <el-input style="width: 115px" v-model="prefix" disabled></el-input>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="英文表名:" v-else>
          <el-input v-model="formData.editName" disabled> </el-input>
        </el-form-item>
        <el-form-item label="选择导入:" prop="exportTable" v-if="dialogSetting.title !== '编辑'">
          <el-select v-model="formData.exportTable">
            <el-option v-for="(item, index) in tableSetting.data" :key="index" :label="item.Name" :value="item.Name" />
          </el-select>
        </el-form-item>
        <el-form-item label="新英文表明:" prop="editNewName" v-else>
          <el-input v-model="formData.editNewName">
            <template #prepend>
              <el-input style="width: 115px" v-model="prefix" disabled></el-input>
            </template>
          </el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogSetting.visible = false">取消</el-button>
          <el-button type="primary" @click="handle"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 底部新增修改弹出框 -->
    <el-dialog v-model="dialogSetting2.visible" :title="dialogSetting2.title" width="30%" draggable>
      <el-form label-width="110px" :model="formData2" :rules="rules2" ref="formRef2">
        <el-form-item label="中文字段名:" prop="ColumnDescription">
          <el-input v-model="formData2.ColumnDescription"></el-input>
        </el-form-item>
        <el-form-item label="英文字段名:" prop="DbColumnName">
          <el-input v-model="formData2.DbColumnName" :disabled="dialogSetting2.title === '编辑' ? true : false"></el-input>
        </el-form-item>
        <el-form-item label="是否是主键:" prop="IsPrimarykey">
          <el-checkbox v-model="formData2.IsPrimarykey"></el-checkbox>
        </el-form-item>
        <el-form-item label="是否允许为空:" prop="IsNullable">
          <el-checkbox v-model="formData2.IsNullable"></el-checkbox>
        </el-form-item>
        <el-form-item label="字段类型:" prop="DataType">
          <el-select v-model="formData2.DataType">
            <el-option
              v-for="item in selectOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
              :disabled="item.disabled"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="字段大小:" prop="Length">
          <el-input type="number" v-model="formData2.Length"></el-input>
        </el-form-item>
        <el-form-item label="默认值:" prop="DefaultValue">
          <el-input v-model="formData2.DefaultValue"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogSetting2.visible = false">取消</el-button>
          <el-button type="primary" @click="handle2"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 列名修改框 -->
    <el-dialog v-model="dialogSetting3.visible" :title="dialogSetting3.title" width="30%" draggable>
      <el-form label-width="110px" :model="formData3" :rules="rules3" ref="formRef3">
        <el-form-item label="旧字段名:" prop="oldColumnName">
          <el-input v-model="formData3.oldColumnName" disabled></el-input>
        </el-form-item>
        <el-form-item label="新字段名:" prop="newColumnName">
          <el-input v-model="formData3.newColumnName"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogSetting3.visible = false">取消</el-button>
          <el-button type="primary" @click="handle3"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="tsx">
import { reactive, ref, onMounted, nextTick } from "vue";
import type { FormInstance, FormRules } from "element-plus";
import useCurrentInstance from "@/utils/useCurrentInstance";
import { exportTable } from "@/utils/exportTable";

const { proxy } = useCurrentInstance();
// 头部搜索字段
const tableSearchString = ref("");
// 底部搜索字段
const searchString = ref("");
// 下拉框选项
const selectOptions = reactive([
  { label: "int", value: "int", disabled: false },
  { label: "datetime", value: "datetime", disabled: false },
  { label: "bool", value: "bool", disabled: false },
  { label: "string", value: "string", disabled: false },
  { label: "long", value: "long", disabled: false },
  { label: "short", value: "short", disabled: false },
  { label: "double", value: "double", disabled: false },
  { label: "byte[]", value: "byte[]", disabled: false }
]);
// 头部表格配置
const tableSetting = reactive({
  columns: [
    { title: "序号", field: "Number", width: "50px" },
    { title: "英文表名", field: "Name", sortable: true },
    { title: "中文表名", field: "Description", sortable: true }
  ],
  data: [] as any,
  sourthTableData: [] as any[]
});
// 底部表格配置
const tableSetting2 = reactive({
  columns: [
    { title: "序号", field: "Number", width: "50px" },
    { title: "中文字段名", field: "ColumnDescription", sortable: true },
    { title: "英文字段名", field: "DbColumnName", sortable: true },
    {
      title: "是否是主键",
      field: "IsPrimarykey",
      sortable: true,
      slots: {
        default: ({ row }: any) => {
          return [<el-checkbox disabled v-model={row.IsPrimarykey} />];
        }
      }
    },
    {
      title: "是否允许为空",
      field: "IsNullable",
      sortable: true,
      slots: {
        default: ({ row }: any) => {
          return [<el-checkbox disabled v-model={row.IsNullable} />];
        }
      }
    },
    { title: "字段类型", field: "DataType", sortable: true },
    { title: "字段大小", field: "Length", sortable: true },
    { title: "默认值", DefaultValue: "Default", sortable: true }
  ],
  data: [] as any[],
  sourthTableData: [] as any[]
});
// 头部弹出框配置
const dialogSetting = reactive({
  visible: false,
  title: ""
});
// 底部弹出框配置
const dialogSetting2 = reactive({
  visible: false,
  title: ""
});
// 修改列名弹出框配置
const dialogSetting3 = reactive({
  visible: false,
  title: ""
});
// 头部表单绑定字段
const formData = reactive({
  Description: "",
  Name: "",
  exportTable: "",
  editName: "",
  editNewName: ""
});
// 底部表单绑定字段
const formData2 = reactive({
  ColumnDescription: "",
  DbColumnName: "",
  IsPrimarykey: false,
  IsNullable: true,
  DataType: "",
  Length: 0,
  DefaultValue: ""
});
// 获取之前选中的数据类型
let selectedValue: any = ref(null);
// 修改列名表单绑定字段
const formData3 = reactive({
  oldColumnName: "",
  newColumnName: ""
});
// 头部表单规则
const rules = reactive<FormRules>({
  Description: [{ required: true, message: "请输入中文名称!", trigger: "blur" }],
  // Name: [{ required: true, message: "请选择导入的表!", trigger: "blur" }],
  Name: [{ required: true, message: "请输入英文名称!", trigger: "blur" }],
  exportTable: [{ required: true, message: "请选择导入的表!", trigger: "blur" }]
});
// 底部表单规则
const rules2 = reactive<FormRules>({
  ColumnDescription: [{ required: true, message: "请输入中文名称!", trigger: "blur" }],
  DbColumnName: [{ required: true, message: "请输入英文名称!", trigger: "blur" }],
  DataType: [{ required: true, message: "请选择字段类型!", trigger: "blur" }]
});
// 修改列名表单规则
const rules3 = reactive<FormRules>({
  newColumnName: [{ required: true, message: "请输入列名!", trigger: "blur" }]
});
// 获取头部表单实例
const formRef = ref<FormInstance>();
// 获取底部表单实例
const formRef2 = ref<FormInstance>();
// 获取修改列名表单实例
const formRef3 = ref<FormInstance>();
// 头部表单英文前置
const prefix = ref("Master_Data_");
// 头部表格单击保存对象
const rowClickObj = ref();
// 底部表格单击保存对象
const rowClickObj2 = ref();
// 添加序号处理
const dataNumberHandle = (arr: any[]) => {
  arr.forEach((item: any, index: number) => {
    item.Number = index + 1;
  });
  return arr;
};
// 获取头部表信息
const getTableData1 = () => {
  proxy.$vueAxios.get("Table/get").then((res: any) => {
    res.List.forEach((item: any, index: number) => {
      item.Number = index + 1;
    });
    tableSetting.data = dataNumberHandle(res.List);
    tableSetting.sourthTableData = res.List;
  });
};
// 获取底部表格
const getTableData2 = (name: string) => {
  proxy.$vueAxios.get("Table/column/get", { tableName: name }).then((res: any) => {
    tableSetting2.data = dataNumberHandle(res.List);
    tableSetting2.sourthTableData = res.List;
  });
};
// 头部表格单击
const rowClick = ({ row }: any) => {
  rowClickObj.value = row;
  getTableData2(row.Name);
};
// 底部表格单击
const rowClick2 = ({ row }: any) => {
  rowClickObj2.value = row;
  selectedValue.value = row.DataType;
};
// 头部新增
const add = () => {
  dialogSetting.title = "新增";
  dialogSetting.visible = true;
  formRef.value?.resetFields();
};
// 底部新增
const add2 = () => {
  dialogSetting2.title = "新增";
  dialogSetting2.visible = true;
  formRef2.value?.resetFields();
  selectOptions.forEach(item => {
    item.disabled = false;
  });
};
// 头部编辑
const edit = () => {
  dialogSetting.title = "编辑";
  dialogSetting.visible = true;
  nextTick(() => {
    formData.Description = rowClickObj.value.Description;
    formData.editName = rowClickObj.value.Name;
  });
};
// 底部编辑
const edit2 = () => {
  dialogSetting2.title = "编辑";
  dialogSetting2.visible = true;
  nextTick(() => {
    formData2.ColumnDescription = rowClickObj2.value.ColumnDescription;
    formData2.DbColumnName = rowClickObj2.value.DbColumnName;
    formData2.IsPrimarykey = rowClickObj2.value.IsPrimarykey;
    formData2.IsNullable = rowClickObj2.value.IsNullable;
    formData2.DataType = rowClickObj2.value.DataType;
    formData2.Length = rowClickObj2.value.Length;
    formData2.DefaultValue = rowClickObj2.value.DefaultValue;
  });
  switch (selectedValue.value) {
    case "string":
      selectOptions.forEach(item => {
        item.value !== "string" ? (item.disabled = true) : (item.disabled = false);
      });
      break;
    case "byte[]":
      selectOptions.forEach(item => {
        item.value !== "byte[]" ? (item.disabled = true) : (item.disabled = false);
      });
      break;
    case "int":
      selectOptions.forEach(item => {
        item.value !== "string" ? (item.disabled = true) : (item.disabled = false);
      });
      break;
    case "datetime":
      selectOptions.forEach(item => {
        item.value !== "string" ? (item.disabled = true) : (item.disabled = false);
      });
      break;
    case "bool":
      selectOptions.forEach(item => {
        item.value !== "string" ? (item.disabled = true) : (item.disabled = false);
      });
      break;
    case "long":
      selectOptions.forEach(item => {
        item.value !== "string" ? (item.disabled = true) : (item.disabled = false);
      });
      break;
    case "short":
      selectOptions.forEach(item => {
        item.value !== "string" ? (item.disabled = true) : (item.disabled = false);
      });
      break;
    case "double":
      selectOptions.forEach(item => {
        item.value !== "string" ? (item.disabled = true) : (item.disabled = false);
      });
      break;
    default:
      break;
  }
};
// 修改列名
const editFiled = () => {
  dialogSetting3.title = "编辑";
  dialogSetting3.visible = true;
  formData3.oldColumnName = rowClickObj2.value.DbColumnName;
};
// 头部删除
const del = () => {
  proxy.$messageBox
    .confirm("确定删除该数据？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    })
    .then(() => {
      proxy.$vueAxios.delete2("Table", [rowClickObj.value.Name]).then((res: any) => {
        if (res.Mark) {
          getTableData1();
          proxy.$message.success("删除成功");
        } else {
          proxy.$message.error("删除失败");
        }
      });
    })
    .catch(err => {
      console.log(err);

      proxy.$message("取消删除");
    });
};
// 底部删除
const del2 = () => {
  proxy.$messageBox
    .confirm("确定删除该数据？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    })
    .then(() => {
      if (rowClickObj2.value.IsPrimarykey) {
        proxy.$message.warning("主键无法删除");
      } else {
        proxy.$vueAxios
          .delete2("Table/column", { tableName: rowClickObj2.value.TableName, columnName: rowClickObj2.value.DbColumnName })
          .then((res: any) => {
            if (res.Mark) {
              getTableData2(rowClickObj.value.Name);
              proxy.$message.success("删除成功");
            } else {
              proxy.$message.error("删除失败");
            }
          });
      }
    })
    .catch(err => {
      console.log(err);

      proxy.$message("取消删除");
    });
};
// 导出表格
const exportData = (type: number) => {
  const columns = type === 1 ? tableSetting.columns : tableSetting2.columns;
  const data = type === 1 ? tableSetting.data : tableSetting2.data;
  exportTable(columns, data);
};
// 头部弹出框确认事件
const handle = () => {
  formRef.value!.validate((isValid: boolean) => {
    if (isValid) {
      if (dialogSetting.title === "新增") {
        proxy.$vueAxios
          .post("Table", [{ name: formData.exportTable, remark: formData.Description, newName: prefix.value + formData.Name }])
          .then((res: any) => {
            if (res.Mark) {
              getTableData1();
            } else {
              proxy.$message.error("新增失败");
            }
            dialogSetting.visible = false;
          });
      } else {
        proxy.$vueAxios
          .put("Table", [{ name: formData.editName, remark: formData.Description, newName: prefix.value + formData.editNewName }])
          .then((res: any) => {
            if (res.Mark) {
              getTableData1();
            } else {
              proxy.$message.error("修改失败");
            }
            dialogSetting.visible = false;
          });
      }
    }
  });
};
// 底部弹出框确认事件
const handle2 = () => {
  formRef2.value!.validate((isValid: boolean) => {
    if (isValid) {
      if (dialogSetting2.title === "新增") {
        proxy.$vueAxios
          .post("Table/column", [
            {
              dbColumnName: formData2.DbColumnName,
              columnDescription: formData2.ColumnDescription,
              defaultValue: formData2.DefaultValue,
              isNullable: formData2.IsNullable,
              isPrimarykey: formData2.IsPrimarykey,
              dataType: formData2.DataType,
              length: formData2.Length,
              tableName: rowClickObj.value.Name
            }
          ])
          .then(() => {
            dialogSetting2.visible = false;
            getTableData2(rowClickObj.value.Name);
          });
      } else {
        proxy.$vueAxios
          .put("Table/column", [
            {
              dbColumnName: formData2.DbColumnName,
              columnDescription: formData2.ColumnDescription,
              defaultValue: formData2.DefaultValue,
              isNullable: formData2.IsNullable,
              isPrimarykey: formData2.IsPrimarykey,
              dataType: formData2.DataType,
              length: formData2.Length,
              tableName: rowClickObj2.value.TableName
            }
          ])
          .then(() => {
            dialogSetting2.visible = false;
            getTableData2(rowClickObj2.value.TableName);
          });
      }
    }
  });
};
// 修改列名确认事件
const handle3 = () => {
  formRef3.value!.validate((isValid: boolean) => {
    if (isValid) {
      proxy.$vueAxios
        .post("Table/RenameColumn", {
          newColumnName: formData3.newColumnName,
          oldColumnName: formData3.oldColumnName,
          tableName: rowClickObj.value.Name
        })
        .then(() => {
          dialogSetting3.visible = false;
          getTableData2(rowClickObj.value.Name);
        });
    }
  });
};
// 头部搜索事件
const onTableSearchChange = () => {
  const filterData = tableSetting.sourthTableData.filter(
    data =>
      data.Name.toLowerCase().includes(tableSearchString.value.toLowerCase()) ||
      (data.Description !== null && data.Description.includes(tableSearchString.value))
  );
  tableSetting.data = filterData;
};
// 底部搜索事件
const onSearchChange = () => {
  const filterData = tableSetting2.sourthTableData.filter(
    data =>
      (data.DbColumnName !== null && data.DbColumnName.toLowerCase().includes(searchString.value.toLowerCase())) ||
      (data.ColumnDescription !== null && data.ColumnDescription.toLowerCase().includes(searchString.value.toLowerCase()))
  );

  tableSetting2.data = filterData;
};
onMounted(() => {
  getTableData1();
});
</script>

<style scoped lang="scss">
@import "./index.scss";
.topSearch {
  position: relative;
  margin-bottom: 12px;
}
.btns {
  margin-left: 40px;
}
.exportBtn {
  position: absolute;
  top: 0;
  right: 0;
}
.cen-search {
  position: relative;
  margin: 26px 0 12px;
}
</style>
